package com.fyzk.activity.forum;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.app.AppToast;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.dialog.SureDialog;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.utils.ImageUtils;
import com.fyzk.utils.LogUtil;
import com.fyzk.view.TopTitleView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.http.body.RequestBody;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import com.wf.domain.UrlDef;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

/**
 * Created by fanxs11 on 17/5/8.
 *
 * 发布帖子
 */

@ContentView(R.layout.ac_posting)
public class PostingActivity extends BaseActivity {

    private String topics = ""; // 话题名称

    @ViewInject(R.id.posting_topview)
    private TopTitleView topView;

    @ViewInject(R.id.posting_title)
    private EditText posting_title_et;

    @ViewInject(R.id.posting_content)
    private PictureAndTextEditorView content_et;

    @ViewInject(R.id.posting_photoalbum)
    private ImageView photoAlbum_iv;

    @ViewInject(R.id.posting_takingpictures)
    private ImageView takingPictures_iv;

    private String sendImgKey = "";

    private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";
    Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION);
    private static final int TAKE_BIG_PICTURE = 0;
    private static final int GET_PICTURE = 1;

    private List<Bitmap> bitmaps = new ArrayList<>();
    private List<String> img_ids = new ArrayList<>();
    private List<PictureAndTextEditorView.ContentInfo> mContentList = new ArrayList<>();

    private boolean isRequesting = false;  // 是否正在发布帖子(防止频繁点击发布按钮)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }

        topics = getIntent().getStringExtra("title");

        initView();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            switch (requestCode) {
                case TAKE_BIG_PICTURE:
                    if (resultCode == 0) {
//                        this.finish();
                    } else {
//                        imgPath = imageUri.getPath();
                        content_et.insertBitmap(imageUri.getPath()+"");
                    }

                    break;
                case GET_PICTURE:
                    if (resultCode == 0) {
//                        this.finish();
                    } else {
                        Uri uri = data.getData();
                        String path = getRealFilePath(getContext(), uri);
//                        imgPath = path;
                        content_et.insertBitmap(path+"");
                    }
                    break;
                default:
                    break;
            }

        } catch (Exception e) {

        }

    }

    private void initView() {
        topView.setOnTitleClickListener(this);
        topView.setRightTxt("发表");
        topView.getRightTxt().setGravity(Gravity.RIGHT);
        topView.getRightTxt().setBackground(null);

        posting_title_et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getKeyCode()==KeyEvent.KEYCODE_ENTER) {
                    AppToast.getToast().show("标题禁止换行");
                    return true;
                }
                return false;
            }
        });

        content_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.i("PostingActivity",content_et.getmContentList().toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        photoAlbum_iv.setOnClickListener(this);
        takingPictures_iv.setOnClickListener(this);

    }

    /**
     *  上传图片（论坛）
     */
    private void sendImg(int command, String imgPath) {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            data.put("attach_access_key", sendImgKey);
            data.put("type", "question");
            data.put("aws_upload_file",ImageUtils.imageZoom(ImageUtils.getSmallBitmap(imgPath), 200));
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_UPLOADIMG);

            params.setBodyContent("req="+ URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, command, params, true);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *  发表帖子（论坛）
     */
    private void postingRequest() {
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("token", MySharedPreferences.getInstance().getAuthtoken());
            request_json.put("time", System.currentTimeMillis());
            JSONObject data = new JSONObject();
            JSONArray array = new JSONArray();
            for (String s: getImageIds()) {
                array.put(s);
            }
            data.put("attach_ids", array);
            data.put("category_id", "1");
            data.put("question_content", posting_title_et.getText().toString());
            data.put("question_detail", getContent());
            data.put("attach_access_key", sendImgKey);
            JSONArray array1 = new JSONArray();
            array1.put(topics);
            data.put("topics", array1);
            request_json.put("data", data);
            LogUtil.d("联网请求json:"+request_json.toString());
            RequestParams params = new RequestParams(UrlDef.FORUM_URL + Commands.FORUM_PUBLISH);

            params.setBodyContent("req="+ URLEncoder.encode(request_json.toString(), "UTF-8"));
            RequestBody body = params.getRequestBody();
            body.setContentType("application/x-www-form-urlencoded");
            params.setRequestBody(body);

            sendRequest(HttpMethod.POST, CommandUtil.FORUM_PUBLISH, params, true);
        } catch (JSONException e) {

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        if (requestCode == CommandUtil.FORUM_PUBLISH) { // 发布帖子返回
//            AppToast.getToast().show("发布成功！");
            showSureDialog();
        } else {    // 上传图片返回
            for (PictureAndTextEditorView.ContentInfo info: mContentList) {
                if (info.type == 1 && requestCode == info.indext) {
                    UploadImageBean bean = JSON.parseObject(resultBean.getData(), UploadImageBean.class);
                    LogUtil.d("bean " + bean.getAttach_id());
                    info.imageId = bean.getAttach_id();
                    resultCount++;
                    if (uploadCount == resultCount) {
                        postingRequest();
                        LogUtil.d("centent: "+getContent());

                    }
                }
            }
        }
    }

    @Override
    protected void onFailure(int requestCode) {
        if (requestCode == CommandUtil.FORUM_PUBLISH) { // 发布帖子返回
            AppToast.getToast().show("发布失败！");
        }
        isRequesting = false;
    }

    private List<String> getImageIds() {
        List<String> imageIds = new ArrayList<>();
        for (int i = 0; i < mContentList.size(); i++) {
            PictureAndTextEditorView.ContentInfo info = mContentList.get(i);
            if (info.type == 1) {
                imageIds.add(info.imageId);
            }
        }
        return imageIds;
    }

    private String getContent() {
        String content = "";
        for (int i = 0; i < mContentList.size(); i++) {
            PictureAndTextEditorView.ContentInfo info = mContentList.get(i);
            if (info.type == 1) {
                content += "[attach]"+info.imageId + "[/attach]";
            } else {
                content += info.content;
            }

        }
        return content;
    }

    @Override
    public void onClick(View arg0) {
        super.onClick(arg0);
        switch (arg0.getId()) {
            case R.id.posting_photoalbum:
                getPictrue();
                break;
            case R.id.posting_takingpictures:
                toPictrue();
                break;
        }
    }

    private int uploadCount = 0;
    private int resultCount = 0;
    @Override
    public void onRightClick() {
        if (isRequesting) {
            return;
        }
        if (!verification()) {
            return;
        }
        isRequesting = true;
        uploadCount = 0;
        resultCount = 0;
        sendImgKey = System.currentTimeMillis()+"";
        mContentList = content_et.getmContentList();
        LogUtil.d("text: "+content_et.getText());
        for (int i = 0; i < mContentList.size(); i++) {
            PictureAndTextEditorView.ContentInfo info = mContentList.get(i);
            LogUtil.d(i+" content: "+info.content + " id:"+info.indext + " type:"+info.type);
            if (info.type == 1) {
                uploadCount++;
                sendImg(info.indext, info.content);
            }
        }
        if (uploadCount == 0) { // 没有图片
            postingRequest();
        }
    }

    private boolean verification() {
        if (TextUtil.isEmpty(posting_title_et.getText().toString())) {
            AppToast.getToast().show("请输入帖子标题");
            return false;
        }

        if (posting_title_et.getText().toString().replaceAll("\\s+","").length() == 0) {
            AppToast.getToast().show("标题不能全部为空格");
            return false;
        }

        if (posting_title_et.getText().toString().length() < 5) {
            AppToast.getToast().show("标题不得少于5个字");
            return false;
        }
//        if (TextUtil.isEmpty(content_et.getText().toString())) {
//            AppToast.getToast().show("帖子内容不能为空");
//            return false;
//        }

        return true;
    }


    /**
     * 拍照
     */
    private void toPictrue() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            String imgName = "img"+System.currentTimeMillis();
            imageUri = Uri.parse("file:///sdcard/"+imgName+".jpg");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, TAKE_BIG_PICTURE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从相册获取
     */
    private void getPictrue() {
        try {
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    "image/*");
            startActivityForResult(intent, GET_PICTURE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver()
                    .openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    private String getRealFilePath(final Context context, final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    SureDialog sureDialog;
    /**
     * 确认支付对话框
     */
    public void showSureDialog() {

        SureDialog.OnDialogOKCancleClickListener listener = new SureDialog.OnDialogOKCancleClickListener() {

            @Override
            public void onOKClick() {
                finish();
                sureDialog.dismiss();
            }

            @Override
            public void onCancleClick() {
                sureDialog.dismiss();
            }
        };

        sureDialog = new SureDialog(this, listener, "发布成功", "", "确定");

        sureDialog.show();
    }
}
